import React, {Component} from 'react';
import GridTable from '../../components/display/gridTable';
import { Button, Input, Select, Row, Col, Popconfirm, Divider, Carousel, Tooltip, message, Spin } from 'antd';
import ScModal from '../../components/feedback/scModal';
import locale from "antd/lib/date-picker/locale/zh_CN";
import {DatePicker} from "antd/lib/index";
import {
  estimateManagment,
  deleteCommend, replyCommend, getOrderDetail
} from '../../fetch/fetchApi';
const Option = Select.Option;
const TextArea = Input.TextArea;
const { RangePicker } = DatePicker;

class CommendMd extends Component {
  constructor () {
    super();
    this.state = {
      gridData: null,
      loadingmes: '查询',
      loading: !1,
      replyContent: '',
      detailData: null,
	  rangeValue: null,
      spinLoading: !1,
      pagination: {
        total: 0
      }
    };
    this.init();
  }

  componentDidMount () {
    this.queryChargeInfo();
  }

  init () {
    this.query = {
      page: '1',
      pagecount: '10'
    };
    this.params = {
      text: ''
    };
    // 设置表头
    this.tableColumns = [
      {
        title: '用户账号',
        dataIndex: 'userAccount',
        key: 'userAccount',
        fixed: 'left',
        width: 100,
      }, {
        title: '电站名称',
        dataIndex: 'stubGroupName',
        key: 'stubGroupName',
      }, {
        title: '电桩编号',
        dataIndex: 'stubId',
        key: 'stubId'
      }, {
        title: '评分',
        dataIndex: 'score',
        key: 'score'
      }, {
        title: '评价内容',
        dataIndex: 'info',
        key: 'info',
        className: 'column-nowrap',
        render: (text, record) => (
          <Tooltip placement="topLeft" title={text} >
            {text}
          </Tooltip>)
      }, {
        title: '图片',
        dataIndex: 'img',
        key: 'img',
        render: (text, record) => (<img onClick={() => this.openThumbModal(record.img, '图片预览', 0)} style={{width:'60px'}} src={record.img && record.img.toString().split(',')[0]}/>)
      }, {
        title: '评价时间',
        dataIndex: 'createTime',
        key: 'createTime',
      }, {
        title: '回复内容',
        dataIndex: 'replayInfo',
        key: 'replayInfo',
        className: 'column-nowrap',
        render: (text, record) => (
          <Tooltip placement="topLeft" title={text} >
            {text}
          </Tooltip>)
      }, {
        title: '操作',
        key: 'action',
        fixed: 'right',
        width: 100,
        render: (text, record) => (
          <div className="action-wrap">
            <a href="javascript:void(0);" onClick={() => this.showOrderDetail(record.orderId, '查看订单')}>查看订单</a>
            <Divider type="vertical" />
            <Popconfirm title="确认要删除么?" onConfirm={() => this.deleteCommend(record.key)} okText="确认" cancelText="取消">
              <a href="javascript:void(0);">删除</a>
            </Popconfirm>
            {!record.replayInfo ? <span><Divider type="vertical" /><a href="javascript:void(0);" onClick={() => this.openInputModal(record.orderId, '回复评价', 1)}>回复</a></span> : ''}
          </div>
        )
      }
    ];
  }

  // 显示订单详情
  showOrderDetail (id, title) {
    this.setState({
      width: 920,
      modalVisible: !0,
      modalTitle: title,
      modalName: 'orderdetail',
      spinLoading: !0
    });
    this.getOrderDetail(id).then(() => {
      this.setState({
        spinLoading: !1
      });
    });
  }

  // fetch 订单详情
  async getOrderDetail (id) {
    try {
      const resData = await getOrderDetail({
        orderId: id
      });
      if (resData.data.code === '200') {
        this.setState({
          detailData: resData.data.data,
          spinLoading: !1
        });
      }
    } catch (e) {
      console.log(e);
    }
  }

  // fetch 评价管理列表
  async estimateManagment () {
    this.setState({
      loading: !0
    });
    try {
      const resData = await estimateManagment(this.query);
      if (resData.data.code === '200') {
        const pagination = {
          total: resData.data.pageLimit.totalCount,
          onShowSizeChange: (current) => {
            this.turnPage(current)
          },
          onChange:(current) => {
            this.turnPage(current)
          }
        }
        this.setState({
          pagination
        });
        return resData.data.data;
      }
    } catch (e) {
      console.log(e);
    }
  }

  // 删除评价
  async deleteCommend (id) {
      try {
        const resData = await deleteCommend({
          id
        });
        resData.data.code === '200' && this.queryChargeInfo();
      } catch (e) {
        console.log(e);
      }
  }

  filterDataHandler (t) {
    return t !== null ? t : '--';
  }

  // 打开输入modal
  openInputModal (id, title, type) {
    this.params['orderId'] = id;
    this.setState({
      width: 520,
      modalTitle: title,
      modalName: 'input'
    }, () => {
      this.setState({
        modalVisible: !0
      });
    });
  }

  // 打开预览
  openThumbModal (imgs, title, type) {
    this.openType = type;
    const imgArr = imgs.toString().split(',');
    const thumbDom = [];
    for (let i of imgArr) {
      i.length && thumbDom.push(<div key={i}><h3><img src={i} /></h3></div>);
    }
    this.setState({
      width: 620,
      modalTitle: title,
      thumbDom: thumbDom,
      modalName: 'thumbPic'
    }, () => {
      this.setState({
        modalVisible: !0
      });
    });
  }

  // 回复评价
  async replyCommend () {
    if (!this.params['text'].toString().trim()) {
      message.warning('内容不能为空', 1);
      return;
    }
    this.setState({
      confirmLoading: !0
    });
    try {
      const resData = await replyCommend(this.params);
      resData.data.code === '200' && this.queryChargeInfo();
    } catch (e) {
      console.log(e);
    }
  }

  // 跳转页码
  turnPage (current) {
    this.query['page'] = current.toString();
    this.estimateManagment().then((data) => {
      this.setState({
        loading: !1,
        gridData: data
      });
    });
  }

  // 提交查询
  queryChargeInfo () {
    this.query.page = '1';
    this.state.pagination.current = 1;
    this.setState({
      pagination: this.state.pagination
    });
    this.estimateManagment().then((data) => {
      this.setState({
        loading: !1,
        gridData: data
      });
    });
  }
  
	// 选择年份
    onDataChange (e) {
		if (e[1]-e[0] > 7 * 24 * 60 * 6e4) {
			message.warn('选择范围请在7天内', 1);
            this.setState({
                'rangeValue': null
            });
            this.query['startTime'] = '';
            this.query['endTime'] = '';
            return;
        };
        this.setState({
            'rangeValue': e
        });
        this.query['startTime'] = e[0] && e[0].format('YYYY-MM-DD HH:mm:ss').toString();
        this.query['endTime'] = e[1] && e[1].format('YYYY-MM-DD HH:mm:ss').toString();
    }

  // 注入账号信息参数
  userInputHandler (e) {
    this.query['account'] = e.target.value.toString();
  }

  // 注入电站名称
  powerStationInputHandler (e) {
    this.query['powerStationName'] = e.target.value.toString();
  }

  // 设置回复内容
  replyInputHandler (e) {
    this.params['text'] = e.target.value;
    this.setState({
      'replyContent': this.params['text']
    })
  }

  // 取消弹窗
  cancel () {
    this.setState({
      modalVisible: !1,
      confirmLoading: !1,
      replyContent: ''
    });
  }

  render () {
    const Content = <div className="sc-page-content">
      <div className="page-toolbar">
        <Row gutter={8}>
          <Col lg={8} xl={4}>
            <Input placeholder="用户账号精确查询" onChange={this.userInputHandler.bind(this)}/>
          </Col>
          <Col lg={8} xl={4}>
            <Input placeholder="电站名称" onChange={this.powerStationInputHandler.bind(this)}/>
          </Col>
		  <Col lg={8} xl={6}>
			<RangePicker value={this.state.rangeValue}
				onChange={this.onDataChange.bind(this)} locale={locale} format="YYYY-MM-DD HH:mm:ss" />
          </Col>
          <Col lg={3} xl={3} >
            <Button type="primary" onClick={this.queryChargeInfo.bind(this)}>{this.state.loadingmes}</Button>
          </Col>
        </Row>
      </div>
      <div className="page-panel">
        <GridTable postyle="table-center" data={this.state.gridData} columns={this.tableColumns} loading={this.state.loading} pagination={this.state.pagination}/>
        {this.state.modalName === 'input' && <ScModal
          width={this.state.width}
          modalVisible={this.state.modalVisible}
          modalTitle={this.state.modalTitle}
          modalContent={(<div className="sc-modal-scroll">
            <div className={'modal-list'}>
              <TextArea placeholder="请输入回复内容" value={this.state.replyContent} onChange={this.replyInputHandler.bind(this)}></TextArea>
            </div>
          </div>)}
          handle = {() => this.replyCommend().then(() => this.cancel())}
          confirmLoading={this.state.confirmLoading}
          cancel={this.cancel.bind(this)}
        />}
        {this.state.modalName === 'thumbPic' && <ScModal
          width={this.state.width}
          modalVisible={this.state.modalVisible}
          modalTitle={this.state.modalTitle}
          modalContent={(<div className="sc-modal-scroll">
            <div className={'modal-list'}>
              <Carousel autoplay>
                {this.state.thumbDom}
              </Carousel>
            </div>
          </div>)}
          cancel={this.cancel.bind(this)}
          footer={null}
        />}
        {
          this.state.modalName === 'orderdetail' && <ScModal
            width={this.state.width}
            modalVisible={this.state.modalVisible}
            modalTitle={this.state.modalTitle}
            modalContent={<div className="sc-modal-scroll">
              {this.state.spinLoading && <Spin className={'loadingMiddle'}/>}
              {this.state.detailData && <div className="modal-list">
                <div className={"modal-flex"}>
                  <div className={"modal-flex-1"}>
                    <ul>
                      <li>
                        <strong>平台订单号:</strong>
                        <span>{this.filterDataHandler(this.state.detailData.id)}</span>
                      </li>
                      <li>
                        <strong>业务订单号:</strong>
                        <span>{this.filterDataHandler(this.state.detailData.outOrderId)}</span>
                      </li>
                      <li>
                        <strong>充电应用:</strong>
                        <span>{this.filterDataHandler(this.state.detailData.appStr)}</span>
                      </li>
                      <li>
                        <strong>充电用户:</strong>
                        <span>{this.filterDataHandler(this.state.detailData.account)}</span>
                      </li>
                      <li>
                        <strong>充电时间:</strong>
                        <span>{this.filterDataHandler(this.state.detailData.timeStart)} - {this.filterDataHandler(this.state.detailData.timeEnd)}</span>
                      </li>
                      <li>
                        <strong>电桩编号:</strong>
                        <span>{this.filterDataHandler(this.state.detailData.stubId)}</span>
                      </li>
                      <li>
                        <strong>电站名称:</strong>
                        <span>{this.filterDataHandler(this.state.detailData.stubGroupName)}</span>
                      </li>
                      <li>
                        <strong>运营类型:</strong>
                        <span>{this.filterDataHandler(this.state.detailData.stubGroupType === 0 ? '非自营': '自营')}</span>
                      </li>
                      <li>
                        <strong>电站城市:</strong>
                        <span>{this.filterDataHandler(this.state.detailData.cityStr)}</span>
                      </li>
                      <li>
                        <strong>支付方式:</strong>
                        <span>{this.filterDataHandler(this.state.detailData.payTypeInfo)}</span>
                      </li>
                    </ul>
                  </div>
                  <div className={"modal-flex-1"}>
                    <ul>
                      <li>
                        <strong>充电电量:</strong>
                        <span>{this.filterDataHandler(this.state.detailData.power)}</span>
                      </li>
                      <li>
                        <strong>充电时长:</strong>
                        <span>{this.filterDataHandler(this.state.detailData.chargeTime)}</span>
                      </li>
                      <li>
                        <strong>充电状态:</strong>
                        <span>{this.filterDataHandler(this.state.detailData.status === 9 ? '充电完成': '充电中')}</span>
                      </li>
                      <li>
                        <strong>订单金额:</strong>
                        <span>{this.filterDataHandler(parseFloat(this.state.detailData.feeTotal) + parseFloat(!this.state.detailData.feeDiscount ? 0 : (this.state.detailData.feeDiscount[0] + this.state.detailData.feeDiscount[1])))}</span>
                      </li>
                      <li>
                        <strong>折扣类型:</strong>
                        <span>{this.filterDataHandler(this.state.detailData.discountTypeStr)}</span>
                      </li>
                      <li>
                        <strong>折扣金额:</strong>
                        <span>{this.filterDataHandler(!this.state.detailData.feeDiscount ? '--' : (this.state.detailData.feeDiscount[0] + this.state.detailData.feeDiscount[1]))}</span>
                      </li>
                      <li>
                        <strong>应付金额:</strong>
                        <span>{this.filterDataHandler(this.state.detailData.feeTotal)}</span>
                      </li>
                      <li>
                        <strong>抵扣金额:</strong>
                        <span>{this.filterDataHandler(this.state.detailData.voucherMoney)}</span>
                      </li>
                      <li>
                        <strong>实付金额:</strong>
                        <span>{this.filterDataHandler(this.state.detailData.accountMoney)}</span>
                      </li>
                      <li>
                        <strong>停止原因:</strong>
                        <span>{this.filterDataHandler(this.state.detailData.endInfo)}</span>
                      </li>
                      <li>
                        <strong>退款状态:</strong>
                        <span>{this.filterDataHandler(this.state.detailData.payType === 2 ? !this.state.detailData.refundStatus ? '无需退款' :
                          (this.state.detailData.refundStatus === 0 ? '退款失败': '退款成功'): '---')}</span>
                      </li>
                    </ul>
                  </div>
                </div>
              </div>}
            </div>}
            footer={null}
            cancel={this.cancel.bind(this)}
          />
        }
      </div>
    </div>;

    return Content;
  }
}

export default CommendMd;